package test.designmode.future;

/**
 * Created by linshuo on 2018/3/4.
 *
 *
 * - FutureData本质就是对RealData的封装;
 * - 用上synchronized,wait,notify是为了保证setRealData执行完了才执行realData.getResult;
 * - Ps: synchronized修饰方法 --> 锁对象为this --> 即使是同一个对象中,getResult和setRealData也不能同时执行;
 */
public class FutureData implements Data {
    private RealData realData;

    private boolean isReady = false;

    @Override
    public synchronized String getResult() {
        while (!isReady) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return realData.getResult();
    }

    public synchronized void setRealData(RealData realData) {
        if (isReady)
            return;
        this.realData = realData;
        isReady = true;
        notifyAll();
    }
}
